﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mysoft.Common.Enum;
using Mysoft.Common.Extensions;
using Mysoft.Data.CacheManager.IService;
using Mysoft.Data.CacheManager.Service;
using Mysoft.Tasks.Queue.IService;
using Mysoft.Tasks.Queue.IService.Attributes;
using Mysoft.Tasks.Queue.IService.Events;
using Mysoft.Tasks.Queue.IService.IEvents;
using Mysoft.Tasks.Queue.RabbitMQ.Extensions;
using RabbitMQ.Client.Events;

namespace Mysoft.Tasks.Queue.RabbitMQ
{
    /// <summary>
    /// 事件总线
    /// </summary>
    internal class RedisMQEventBus : IMQEventBus
    {
        private readonly ILogger<RedisMQEventBus> _logger;
        private readonly IServiceProvider _serviceProvider;
        private readonly ICacheService _cacheService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="serviceProvider"></param>
        /// <param name="cacheService"></param>
        public RedisMQEventBus(ILogger<RedisMQEventBus> logger, IServiceProvider serviceProvider, ICacheService cacheService)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
            _cacheService = cacheService;
        }
        /// <summary>
        /// 消息队列中间件
        /// </summary>
        /// <returns></returns>
        public string GetMode()
        {
            return "Redis";
        }
        /// <summary>
        /// 验证Redis是否启用
        /// </summary>
        /// <returns></returns>
        public bool CheckRedis()
        {
            bool isRedis = _cacheService is RedisCacheService;
            return isRedis;
        }
        
        /// <summary>
        /// 推送延时消息
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="message"></param>
        /// <param name="queue"></param>
        /// <param name="exchange"></param>
        /// <param name="routingKey"></param>
        /// <param name="deadExchange"></param>
        /// <param name="deadRoutingKey"></param>
        /// <param name="delay"></param>
        /// <param name="QueryType"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void DelayedPublish<TMessage>(TMessage message, string queue, string exchange, string routingKey, string deadExchange, string deadRoutingKey, int delay, DeadQueryType QueryType = DeadQueryType.message, string type = "topic")
        {
            if (!CheckRedis()) 
            {
                throw new NotImplementedException("消息队列中间件是Redis,但未启用Redis");
            }
            throw new NotImplementedException("Redis模式未实现此功能");
        }

        
        /// <summary>
        /// 推送消息
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="message"></param>
        /// <param name="exchange"></param>
        /// <param name="routingKey"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Publish<TMessage>(TMessage message, string exchange, string routingKey, string type = "topic")
        {
            if (!CheckRedis())
            {
                throw new NotImplementedException("消息队列中间件是Redis,但未启用Redis");
            }
            _cacheService.LPush(exchange, message.ToJson());
            //throw new NotImplementedException("Redis未实现此功能");
        }

        /// <summary>
        /// 队列订阅 轮询队列，后期在升级阻塞模式
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="type"></param>
        public async void Subscribe(Type eventType, string type = "topic")
        {
            if (!CheckRedis())
            {
                return;
            }
            var attributes = eventType.GetCustomAttributes(typeof(EventBusAttribute), true);
            foreach (var attribute in attributes)
            {
                if (attribute is EventBusAttribute attr)
                {
                    string queue = attr.Queue ?? $"{ attr.Exchange }";
                    await Task.Run(async () =>
                    {
                        while (true)
                        {

                            object obj = _cacheService.ListDequeue(queue);
                            while (obj == null)
                            {
                                //需要轮询，降低轮询速度
                                await Task.Delay(10000);
                                obj = _cacheService.ListDequeue(queue);
                            }

                            string body = obj == null ? "" : obj.ToString();
                            try
                            {
                                await ProcessEvent(body, eventType);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(new EventId(ex.HResult), ex, ex.Message);
                            }
                        }
                    });
                }
            }
           
          
            //throw new NotImplementedException("Redis未实现此功能");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="body"></param>
        /// <param name="eventType"></param>
        /// <param name="eventHandleType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private async Task ProcessEvent(string body, Type eventType)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                foreach (Type eventHandleType in typeof(IEventHandler<>).GetMakeGenericType(eventType))
                {
                    object eventHandler = scope.ServiceProvider.GetRequiredService(eventHandleType);
                    if (eventHandler == null)
                    {
                        throw new InvalidOperationException(eventHandleType.Name);
                    }
                    Type concreteType = typeof(IEventHandler<>).MakeGenericType(eventType);
                    await (Task)concreteType.GetMethod(nameof(IEventHandler<IEvent>.Handle)).Invoke(
                       eventHandler,
                       new object[] {
                         Activator.CreateInstance(typeof(EventHandlerArgs<>).MakeGenericType(eventType), new object[] { body,false, "", "" })
                       });
                }
            }
        }
    }
}
